package com.ruoyi.projects.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.constant.BuConstants;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.projects.Vos.WxUserInfoDTO;
import com.ruoyi.projects.domain.SlActivityReports;
import com.ruoyi.projects.mapper.SlActivityReportsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.projects.mapper.SlActivitysMapper;
import com.ruoyi.projects.domain.SlActivitys;
import com.ruoyi.projects.service.ISlActivitysService;

/**
 * 店内活动Service业务层处理
 * 
 * @author yangz
 * @date 2024-12-01
 */
@Service
public class SlActivitysServiceImpl implements ISlActivitysService 
{
    @Autowired
    private SlActivitysMapper slActivitysMapper;

    @Autowired
    private SlActivityReportsMapper slActivityReportsMapper;

    /**
     * 查询店内活动
     * 
     * @param id 店内活动主键
     * @return 店内活动
     */
    @Override
    public SlActivitys selectSlActivitysById(Long id)
    {
        return slActivitysMapper.selectSlActivitysById(id);
    }

    /**
     * 查询店内活动列表
     * 
     * @param slActivitys 店内活动
     * @return 店内活动
     */
    @Override
    public List<SlActivitys> selectSlActivitysList(SlActivitys slActivitys)
    {
        return slActivitysMapper.selectSlActivitysList(slActivitys);
    }

    /**
     * 新增店内活动
     * 
     * @param slActivitys 店内活动
     * @return 结果
     */
    @Override
    public int insertSlActivitys(SlActivitys slActivitys)
    {
        slActivitys.setCreateTime(DateUtils.getNowDate());
        return slActivitysMapper.insertSlActivitys(slActivitys);
    }

    /**
     * 修改店内活动
     * 
     * @param slActivitys 店内活动
     * @return 结果
     */
    @Override
    public int updateSlActivitys(SlActivitys slActivitys)
    {
        slActivitys.setUpdateTime(DateUtils.getNowDate());
        return slActivitysMapper.updateSlActivitys(slActivitys);
    }

    /**
     * 批量删除店内活动
     * 
     * @param ids 需要删除的店内活动主键
     * @return 结果
     */
    @Override
    public int deleteSlActivitysByIds(Long[] ids)
    {
        return slActivitysMapper.deleteSlActivitysByIds(ids);
    }

    /**
     * 删除店内活动信息
     * 
     * @param id 店内活动主键
     * @return 结果
     */
    @Override
    public int deleteSlActivitysById(Long id)
    {
        return slActivitysMapper.deleteSlActivitysById(id);
    }

    /**
     * 查询最新的活动
     * @return
     */
    @Override
    public SlActivitys selectNewActivity() {
        return slActivitysMapper.selectNewActivity();
    }

    /**
     * 活动报名
     */
    @Override
    public ApiResult slActivitySignUp(WxUserInfoDTO dto, Long activityId) {
        SlActivitys slActivitys = slActivitysMapper.selectSlActivitysById(activityId);
        if (slActivitys != null) {
            // 2. 校验活动是否已上架
            if (!BuConstants.FLAG_YES.equals(slActivitys.getIfFlag())) {
                return ApiResult.error(ApiResult.EnumCode.ERROR, "活动未上架，无法报名");
            }

            // 3. 校验活动时间是否有效（当前时间在活动期间内）
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime startTime = slActivitys.getActivityStartTime()
                    .toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            LocalDateTime endTime = slActivitys.getActivityEndTime()
                    .toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

            if (now.isBefore(startTime)) {
                return ApiResult.error(ApiResult.EnumCode.ERROR, "活动尚未开始，无法报名");
            }
            if (now.isAfter(endTime)) {
                return ApiResult.error(ApiResult.EnumCode.ERROR, "活动已结束，无法报名");
            }

            // 4. 校验用户是否已报名（防止重复报名）
            SlActivityReports slActivityReports = new SlActivityReports();
            slActivityReports.setActivityId(activityId);
            slActivityReports.setCustomerId(dto.getId());
            List<SlActivityReports> slActivityReportsList = slActivityReportsMapper
                    .selectSlActivityReportsList(slActivityReports);
            if (slActivityReportsList != null&&slActivityReportsList.size()>0) {
                return ApiResult.error(ApiResult.EnumCode.ERROR, "您已报名该活动，无需重复报名");
            }

            try {
                // 5. 组装报名记录
                SlActivityReports report = new SlActivityReports();
                report.setActivityId(activityId);
                report.setCustomerId(dto.getId());
                report.setActivityName(slActivitys.getActivityName()); // 从活动信息获取
                report.setActivityImg(slActivitys.getActivityImg());   // 从活动信息获取
                report.setCustomerName(dto.getNickName());             // 从用户信息获取
                report.setCustomerAvatar(dto.getAvatarUrl());          // 从用户信息获取
                report.setIfDone(BuConstants.FLAG_NO); // 初始状态：未参加
                report.setCreateTime(new Date()); // 设置报名时间
                report.setCreateBy(dto.getNickName()); // 设置创建人
                // 6. 保存报名记录
                slActivityReportsMapper.insertSlActivityReports(report);

                return ApiResult.success("报名成功");
            } catch (Exception e) {
                // 7. 处理异常情况
                return ApiResult.error(ApiResult.EnumCode.ERROR, "报名失败：" + e.getMessage());
            }
        }else {
            return ApiResult.error(ApiResult.EnumCode.ERROR,"活动不存在");
        }
    }

    /**
     * 查询活动记录同时携带用户信息判断是否已报名
     * @param userId
     * @return
     */
    @Override
    public List<SlActivitys> selectSlActivitysAboutRecords(Long userId) {
        return slActivitysMapper.selectSlActivitysAboutRecords(userId);
    }
}
